/**
 * @file utils
 * @author lishaohai
 */
import moment from 'moment';

export function revolution(startDate, endDate, dateDay) {
    if (new Date(startDate) > new Date(endDate)) {
        return [];
    }

    // dateDay === 1~28 整数
    const numbers = new Array(28).fill('').map((c, i) => i + 1);
    if (!numbers.includes(dateDay)) {
        return [];
    }

    const [startYear, startMonth, startDay] = moment(startDate)
        .format('YYYY-MM-DD')
        .split('-');
    const [endYear, endMonth, endDay] = moment(endDate)
        .format('YYYY-MM-DD')
        .split('-');

    const count = endYear - startYear;

    const startArr = new Array(12 - startMonth + 1)
        .fill('')
        .map((c, index) => moment(startDate).format(`YYYY/${index + 1}/${dateDay}`));
    const endArr = new Array(endMonth - 0)
        .fill('')
        .map((c, index) => moment(endDate).format(`YYYY/${index + 1}/${dateDay}`));

    let dateRange = [];

    if (endDay > dateDay) {
        const lastEl = endArr[endArr.length - 1];
        endArr.push(
            moment(lastEl)
                .add(1, 'months')
                .format('YYYY/MM/DD')
        );
    }

    if (startDay <= dateDay) {
        const lastEl = endArr[0];
        endArr.unshift(
            moment(lastEl)
                .add(-1, 'months')
                .format('YYYY/MM/DD')
        );
    }
    if (count <= 1) {
        // 同年
        const endLastItem = endArr[endArr.length - 1];

        dateRange = [...startArr.filter(i => new Date(i) <= new Date(endLastItem)), ...endArr];
    } else {
        const middleDate = new Array(count - 1).fill('').map((item, index) => {
            const curYear = startYear - 0 + index + 1;
            return new Array(12)
                .fill('')
                .map((c, cindex) => moment(`${curYear}/${cindex + 1}/${dateDay}`).format('YYYY/MM/DD'));
        });

        dateRange = [...startArr, ...middleDate.reduce((acc, cur) => acc.concat(cur), []), ...endArr];
    }

    const unique = arr => [...new Set(arr.map(i => moment(i).format('YYYY/MM/DD')))];

    const result = unique(dateRange).sort((a, b) => new Date(a) - new Date(b));

    const output = [];
    for (let i = 0; i < result.length; i++) {
        if (i >= result.length - 1) {
            break;
        }
        const element = result[i];
        output.push([element, result[i + 1]]);
    }

    // 这里可能会出现: [["2021/01/15","2021/01/15"], ["2021/01/15","2021/01/16"]]
    output[0][0] = moment(startDate).format('YYYY/MM/DD');

    output[output.length - 1][1] = moment(endDate).format('YYYY/MM/DD');

    return output;
}

// console.log('111', revolution('2021/1/16', '2021/2/1', 15)); // ['1/1 ~ 1/15']
// console.log('222', revolution('2021/1/11', '2021/1/11', 15)); // ['1/1 ~ 1/15']
// console.log('333', revolution('2021/1/15', '2021/1/15', 15)); // ['1/1 ~ 1/15']
// console.log('444', revolution('2021/1/15', '2021/2/15', 15)); // ['1/1 ~ 1/15']
// console.log('555', revolution('2021/1/15', '2021/1/16', 15));
// [["2021/01/15","2021/01/15"], ["2021/01/15","2021/01/16"]]

// console.log('666', revolution('2021/1/1', '2021/1/16', 15)); // ['1/1 ~ 1/15']
// console.log('222', revolution('2021/1/1', '2021/1/15', 15)); // ['1/1 ~ 1/15', '1/16 - 1/16']
// console.log('333', revolution('2021/1/1', '2023/3/1', 15)); // ['1/1 ~ 1/15', '1/16 ~ 2/15', '2/16 - 3/1']

// 深拷贝
export function deepCopy(obj, cache = []) {
    function find(list, f) {
        return list.filter(f)[0];
    }

    // just return if obj is immutable value
    if (obj === null || typeof obj !== 'object') {
        return obj;
    }

    // if obj is hit, it is in circular structure
    const hit = find(cache, c => c.original === obj);
    if (hit) {
        return hit.copy;
    }
    const copy = Array.isArray(obj) ? [] : {};
    // put the copy into cache a first
    // because we want to refer it in recursive deepCopy
    cache.push({original: obj, copy});

    Object.keys(obj).forEach(key => {
        copy[key] = deepCopy(obj[key], cache);
    });
    return copy;
}

/**
 *
 * @param {Number} P 本金
 * @param {Number} R 月利率
 * @param {Number} n 分期总数
 * @param {Number} D 日利率
 */
// 每月还款额= P * (R * Math.pow((1 + R), n))/(Math.pow((1 + R), n) - 1)
// 等额本息计算
export function equivalentPrincipal(P, D, n, type) {
    // 年利率 = 日利率 * 360
    // const R = 年利率 / 12
    // const R = (日利率 * 360) / 12
    let R;
    if (type === 'month') {
        // 月利率
        R = D;
    } else if (type === 'year') {
        R = (D * 0.01 * 10000) / (12 * 10000);
    } else {
        // 日利率
        R = (D * 360 * 10000) / (12 * 10000);
    }
    const output = (P * (R * Math.pow(1 + R, n))) / (Math.pow(1 + R, n) - 1);
    return output;
}
const total = 5000;
const num = 12;
const data = equivalentPrincipal(total, 0.097 * 0.01, num);
// const output = Math.floor(data * 100) / 100;
const output = data.toFixed(2);
// console.log('借款 :', total);
// console.log('总还款金额 :', (output * num * 100) / 100);
// console.log('总还款利息 :', ((total - (output * num * 100) / 100) * 100) / 100);
// console.log('每月还款金额 :', output);

// 初始化时间段
export function initDateRange(startDay = 15, endDay = 15, current = new Date()) {
    // 求 defaultEndDate
    // 1. 获取当前年、月
    // 2. 日期 为15号
    // 求defaultStartDate
    // 3. 根据 defaultEndDate 往后推算32天
    // 4. 获取年月
    // 5. 日期为15号即可
    const defaultEndDate = `${moment(current).format('YYYY-MM')}-${endDay}`;
    const t2 = new Date(defaultEndDate).getTime() - 3600 * 1000 * 24 * 32;
    const defaultStartDate = `${moment(t2).format('YYYY-MM')}-${startDay}`;
    return [defaultStartDate, defaultEndDate];
}

/** * 是否为mac系统（包含iphone手机） * */
export function isMac() {
    return /macintosh|mac os x/i.test(navigator.userAgent);
}

/** * 是否为windows系统 * */
export function isWindows() {
    return /windows|win32/i.test(navigator.userAgent);
}

/**
 * @description 查看css计算样式
 * @param {DOM} elem 需要查看样式的DOM对象
 * @param {string, undefind} prop 样式的属性
 */
export function getStyles(elem, prop) {
    // IE8及一下浏览器不支持 getComputedStyle
    // 使用elem.currentStyle
    if (window.getComputedStyle) {
        if (prop) {
            return window.getComputedStyle(elem, null)[prop];
        } else {
            return window.getComputedStyle(elem, null);
        }
    } else {
        if (prop) {
            return elem.currentStyle[prop];
        } else {
            return elem.currentStyle;
        }
    }
}

export function isMobile() {
    return !!navigator.userAgent.match(
        // eslint-disable-next-line
        /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
    );
}

export function isWeixin() {
    return navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1;
}

export function thousands(num) {
    const str = num.toString();
    const reg = str.indexOf('.') > -1 ? /(\d)(?=(\d{3})+\.)/g : /(\d)(?=(?:\d{3})+$)/g;
    return str.replace(reg, '$1,');
}
